package com.web.cloud.service.sm;

import com.web.cloud.constances.DBConsts;
import com.web.cloud.constances.ModelConsts;
import com.web.cloud.dao.sm.SmRoleDao;
import com.web.cloud.exception.BusinessException;
import com.web.cloud.model.sm.SmOrg;
import com.web.cloud.model.sm.SmRole;
import com.web.cloud.service.pub.OrgBaseService;
import com.web.cloud.utils.CommonConsts;
import com.web.cloud.utils.IdGenerator;
import com.web.cloud.utils.OrgInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by liuhaiming on 2015/8/14
 */
@Service
public class SmRoleService extends OrgBaseService<SmRole> {
    @Autowired
    private HttpSession session;

    public SmRoleDao getDao() {
        return (SmRoleDao) this.dao;
    }

    public String getModuleCode() {
        return ModelConsts.MODEL_SM;
    }

    public List<SmRole> selectByIds(List<String> roleLst) {
        return getDao().selectByIds(roleLst.toArray(new String[roleLst.size()]));
    }

    public List<SmRole> selectStatusEnable(int userType) {
        List<SmRole> roleList = null;
        if ( userType == CommonConsts.USER_TYPE_SYSTEM_ADMIN ) {
            roleList = getDao().selectStatusEnableAdmin();
        } else {
            roleList = getDao().selectStatusEnable( OrgInfoHolder.getOrgId() );
        }

        return roleList;
    }

    @Transactional( rollbackFor = {Exception.class} )
    public void createRoleByOrg(SmOrg smOrg) {
        SmRole role = new SmRole();
        role.setOrgId(smOrg.getId());
        role.setCode(smOrg.getCode() + "_admin");
        role.setName(smOrg.getName() + "组织管理员");
        role.setMemo("系统自动生成组织级管理员");
        role.setId(IdGenerator.getInstance().nextId(getModuleCode()));
        role.setIsAdmin(CommonConsts.BOOLEAN_TRUE);
        role.setStatus(DBConsts.STATUS_ENABLE);
        role.setDr(DBConsts.DR_NORMAL);
        role.setTs(Long.valueOf((new Date()).getTime()));
        getDao().insert(role);
    }

    @Override
    public int save(SmRole entity) throws BusinessException {
        try {
            entity.setId(IdGenerator.getInstance().nextId(this.getModuleCode()));
            entity.setDr(DBConsts.DR_NORMAL);
            this.setNewTs(entity);
            int result = this.dao.insert(entity);
            return result;
        } catch (Exception var4) {
            throw new BusinessException(var4);
        }
    }
}

